package com.nbsaas.boot.express.ext.resource;

import cn.binarywang.wx.miniapp.api.WxMaImmediateDeliveryService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.delivery.FollowWaybillRequest;
import cn.binarywang.wx.miniapp.bean.delivery.FollowWaybillResponse;
import cn.binarywang.wx.miniapp.bean.delivery.GetDeliveryListResponse;
import cn.binarywang.wx.miniapp.bean.delivery.WaybillGoodsInfo;
import cn.binarywang.wx.miniapp.bean.express.WxMaExpressDelivery;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.nbsaas.boot.config.ext.apis.ConfigExtApi;
import com.nbsaas.boot.express.ext.apis.ExpressExtApi;
import com.nbsaas.boot.express.ext.domain.request.ExpressSendRequest;
import com.nbsaas.boot.express.ext.domain.simple.DeliverySimple;
import com.nbsaas.boot.order.api.apis.OrderAddressApi;
import com.nbsaas.boot.order.api.apis.OrderApi;
import com.nbsaas.boot.order.api.apis.OrderItemApi;
import com.nbsaas.boot.order.api.domain.field.OrderAddressField;
import com.nbsaas.boot.order.api.domain.field.OrderItemField;
import com.nbsaas.boot.order.api.domain.request.OrderRequest;
import com.nbsaas.boot.order.api.domain.response.OrderAddressResponse;
import com.nbsaas.boot.order.api.domain.response.OrderResponse;
import com.nbsaas.boot.order.api.domain.simple.OrderItemSimple;
import com.nbsaas.boot.rest.filter.Filter;
import com.nbsaas.boot.rest.response.ListResponse;
import com.nbsaas.boot.rest.response.ResponseObject;
import com.nbsaas.boot.shop.ext.apis.ShopConfigExtApi;
import com.nbsaas.boot.shop.ext.domain.config.WeChatOauth;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class ExpressExtResource implements ExpressExtApi {

    @Resource
    private OrderApi orderApi;

    @Resource
    private ShopConfigExtApi shopConfigExtApi;

    @Resource
    private OrderAddressApi orderAddressApi;

    @Resource
    private OrderItemApi orderItemApi;

    @Override
    public ListResponse<DeliverySimple> list(Long shop) {
        ListResponse<DeliverySimple> result=new ListResponse<>();
        result.setData(new ArrayList<>());

        WxMaService maService = new WxMaServiceImpl();

        ResponseObject<WeChatOauth> res = shopConfigExtApi.info(shop, WeChatOauth.class);
        if (res.getCode() != 200) {
            result.setCode(res.getCode());
            result.setMsg(res.getMsg());
            return result;
        }

        WeChatOauth weChatOauth = res.getData();
        if (weChatOauth == null) {
            result.setCode(501);
            result.setMsg("未配置微信公众号信息");
            return result;
        }
        if (!StringUtils.hasText(weChatOauth.getAppSecret())) {
            result.setCode(502);
            result.setMsg("未配置微信公众号信息");
            return result;
        }

        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(weChatOauth.getAppKey());
        config.setSecret(weChatOauth.getAppSecret());
        maService.setWxMaConfig(config);


        try {
            GetDeliveryListResponse ls = maService.getWxMaImmediateDeliveryService().getDeliveryList();
            for (GetDeliveryListResponse.DeliveryList item : ls.getDeliveryList()) {
                DeliverySimple simple=new DeliverySimple();
                simple.setId(item.getDeliveryId());
                simple.setName(item.getDeliveryName());
                result.getData().add(simple);
            }

        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

        return result;
    }

    @Transactional
    @Override
    public ResponseObject<?> send(ExpressSendRequest request) {
        ResponseObject<?> result=new ResponseObject<>();
        OrderResponse order = orderApi.oneData(Filter.eq("id", request.getOrderId()));
        if (order == null){
            result.setMsg("订单不存在");
            result.setCode(503);
            return result;
        }

        if (order.getState() != 2) {
            result.setMsg("订单状态不允许发货");
            result.setCode(504);
            return result;
        }

        WxMaService maService = new WxMaServiceImpl();

        ResponseObject<WeChatOauth> res = shopConfigExtApi.info(request.getShop(), WeChatOauth.class);
        if (res.getCode() != 200) {
            result.setCode(res.getCode());
            result.setMsg(res.getMsg());
            return result;
        }

        WeChatOauth weChatOauth = res.getData();
        if (weChatOauth == null) {
            result.setCode(501);
            result.setMsg("未配置微信公众号信息");
            return result;
        }
        if (!StringUtils.hasText(weChatOauth.getAppSecret())) {
            result.setCode(502);
            result.setMsg("未配置微信公众号信息");
            return result;
        }

        OrderAddressResponse address = orderAddressApi.oneData(Filter.eq(OrderAddressField.order, request.getOrderId()));
        if (address == null){
            result.setMsg("收货地址不存在");
            result.setCode(505);
            return result;
        }

        List<OrderItemSimple> items = orderItemApi.listData(Filter.eq(OrderItemField.order, request.getOrderId()));

        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(weChatOauth.getAppKey());
        config.setSecret(weChatOauth.getAppSecret());
        maService.setWxMaConfig(config);
        WxMaImmediateDeliveryService deliveryService = maService.getWxMaImmediateDeliveryService();


        FollowWaybillRequest req=new FollowWaybillRequest();
        req.setOpenid(order.getOpenId());
        req.setOrderDetailPath(weChatOauth.getOrderDetailPath());
        req.setSenderPhone(weChatOauth.getSenderPhone());
        req.setReceiverPhone(address.getPhone());
        req.setDeliveryId(request.getExpressCode());
        req.setWaybillId(request.getWaybillId());
        req.setTransId(order.getPayNo());

        WaybillGoodsInfo goodsInfo=new WaybillGoodsInfo();
        goodsInfo.setGoodsItemList(new ArrayList<>());
        for (OrderItemSimple item : items) {
            WaybillGoodsInfo.GoodsItem goodsItem=new WaybillGoodsInfo.GoodsItem();
            goodsItem.setGoodsName(item.getProductName());
            goodsItem.setGoodsDesc(item.getProductName());
            goodsItem.setGoodsImgUrl(item.getProductImageUrl());
        }

        req.setGoodsInfo(goodsInfo);


        try {
            FollowWaybillResponse deliveryRes = deliveryService.followWaybill(req);

            OrderRequest orderRequest=new OrderRequest();
            orderRequest.setId(order.getId());
            orderRequest.setExpressCode(request.getExpressCode());
            orderRequest.setExpressName(request.getExpressName());
            orderRequest.setWaybillId(request.getWaybillId());
            orderRequest.setExpressType(request.getExpressType());
            orderRequest.setState(3);
            orderRequest.setShippingTime(new Date());
            orderRequest.setWaybillToken(deliveryRes.getWaybillToken());
            orderApi.update(orderRequest);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

        return result;
    }
}
